/**
 * Created by John on 2016/7/11.
 */
function displayWords(cursor) {
    var words = cursor.map(function (word) {
        return word.word + "(" + word.size + ")";
    });

    var wordStr = JSON.stringify(words);
    if (wordStr.length > 23) {
        wordStr = wordStr.slice(0, 20) + '...';
    }
    print(wordStr);
}

var mongo = new Mongo("localhost");
var wordsDB = mongo.getDB("BeginningMongoDB");
wordsColl = wordsDB.getCollection("word_stats");

wordsDB.runCommand({getLastError: 1, w: 1, j: true, wtimeout: 1000});

var SYwordsCategory = {category: 'SYwords'};
var cursor = wordsColl.find(SYwordsCategory);
print('Before SYwords Update:');
displayWords(cursor);

var query = {$and: [{first: 's'}, {last: 'y'}]};
var update = {$set: {category: 'SYwords'}};
wordsColl.update(query, update, false, true);
cursor = wordsColl.find(SYwordsCategory);
print('After SYwords Update:');
displayWords(cursor);

var say = {word: 'say'};
var projection = {word: 1, size: 1, letters: 1, stats: 1, category: 1}
var word = wordsColl.findOne(say, projection);
print('Before Say Update:');
printjson(word);

var says = {word: 'says'};
var setSay = {
    $set: says,
    $inc: {size: 1, 'stats.consonants': 1},
}
wordsColl.update(say, setSay, false, false);
word = wordsColl.findOne(says, projection);
print('After Say Update:');
printjson(word);

var noneCategory = {category: 'none'};
wordsColl.update(SYwordsCategory, {$set: noneCategory}, false, true);
wordsColl.update(says, {$set: say, $inc: {size: -1, 'stats.consonants': -1}});
word = wordsColl.findOne(say, projection);
print('After Says Update:')
printjson(word);
